package aitrade.trade;

import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.net.ssl.ExtendedSSLSession;

import org.apache.log4j.Logger;

import com.tokenmaster.aitrade.common.account.Account;
import com.tokenmaster.aitrade.common.system.KLinePoint;
import com.tokenmaster.aitrade.common.ticker.Ticker_Spot;
import com.tokenmaster.aitrade.data.SystemDB;
import com.tokenmaster.aitrade.market.okex.Market_Okex_Spot;
import com.tokenmaster.aitrade.trade.kdj.Index_KDJ_Info;

public class AiTrade {

	private Logger logger = Logger.getLogger(this.getClass());

	private Account account = new Account("小布", "1", "BTC");

	private SystemDB systemDB = SystemDB.getInstance();

	// 最后一条 K 线
	private KLinePoint last_KLinePoint_Short = null;
	private KLinePoint last_KLinePoint_Mid = null;

	// 现货市场
	Market_Okex_Spot market_Okex_Spot = Market_Okex_Spot.getInstance();

	private String symbol = "btc_usdt";
	private String type_short = "15min";
	private String type_mid = "4hour";

	private String runMode = "formal";

	private long lastOperationTime = 0;

	// 循环执行
	public void doWork() throws IOException {

		// 获取最后一条 K 线
		last_KLinePoint_Short = systemDB.getLastKLinePoint(symbol, type_short);
		last_KLinePoint_Mid = systemDB.getLastKLinePoint(symbol, type_mid);

		if (last_KLinePoint_Short == null || last_KLinePoint_Mid == null)
			return;

		// 获取短线KDJ
		Index_KDJ_Info index_KDJ_Info_short = systemDB.getIndexKDJ(symbol, type_short,
				last_KLinePoint_Short.getUnixTime());

		// 获取中线KDJ
		Index_KDJ_Info kdj_Info_Long = systemDB.getLastIndexKDJ(symbol, type_mid, last_KLinePoint_Mid.getUnixTime());

		// 判断KDJ指标是否符合买卖条件
		checkTradeCondition_KDJ(index_KDJ_Info_short, kdj_Info_Long);

		double lastUnixTime = last_KLinePoint_Short.getUnixTime();
		SimpleDateFormat sformat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
		String timestr = sformat.format(lastUnixTime);

		double totalAsset = account.getTotalAsset(last_KLinePoint_Short.getLast());
		logger.info(timestr + "总资产:" + Math.floor(totalAsset));

	}

	/**
	 * 检查KDJ指标
	 * 
	 * @param kLinePoint
	 * @param index_KDJ_Info
	 * @param kdj_Info_Long
	 */
	private void checkTradeCondition_KDJ(Index_KDJ_Info kdj_Info_Short, Index_KDJ_Info kdj_Info_Mid) {

		// 操作间隔不小于15分钟
		if (last_KLinePoint_Short.getUnixTime() < lastOperationTime + 5 * 60 * 1000) {
			return;
		}

		// 获取上次短线KDJ
		Index_KDJ_Info kdj_Info_Before = systemDB.getLastIndexKDJ(symbol, type_short,
				last_KLinePoint_Short.getUnixTime());

		// 买币花费
		double buy_cost = 0;

		// 判断短线低位金叉
		if (kdj_Info_Before.getkValue() < kdj_Info_Before.getdValue()
				&& kdj_Info_Short.getkValue() > kdj_Info_Short.getdValue() && kdj_Info_Short.getkValue() < 50) {

			logger.info("短线低位金叉(K,D):" + kdj_Info_Short.getkValue() + "|" + kdj_Info_Short.getdValue());

			if (kdj_Info_Mid.getdValue() > 60) {
				logger.info("价格较高,不再买入.中线(K,D)" + kdj_Info_Mid.getkValue() + "|" + kdj_Info_Mid.getdValue());
				return;
			} else if (kdj_Info_Mid.getkValue() >= kdj_Info_Mid.getdValue()) {
				// 中线上升趋势
				logger.info("中线上升趋势:" + kdj_Info_Mid.getkValue() + "|" + kdj_Info_Mid.getdValue());

				buy_cost = buy_cost + 5000;

				// 低于平均购入成本，加倍买进
				double avg_price = account.getAvg_price();
				if (avg_price != 0 && last_KLinePoint_Short.getLast() / avg_price < 0.95) {
					buy_cost = buy_cost + 5000;
				}
			} else if (kdj_Info_Mid.getkValue() < kdj_Info_Mid.getdValue()) {

				// 中线下降通道,可以尝试吃货,最多1/5仓位
				if (account.getPosition() > 0.2)
					return;

				buy_cost = buy_cost + 5000;

				// 低于平均购入成本，加倍买进
				double avg_price = account.getAvg_price();
				if (avg_price != 0 && last_KLinePoint_Short.getLast() / avg_price < 0.95) {
					buy_cost = buy_cost + 5000;
				}
			}

			account.buyCoinByMoney(last_KLinePoint_Short.getLast(), buy_cost, System.currentTimeMillis());
			lastOperationTime = last_KLinePoint_Short.getUnixTime();
		}
		// 短线死叉
		else if (kdj_Info_Before.getkValue() > kdj_Info_Before.getdValue()
				&& kdj_Info_Short.getkValue() < kdj_Info_Short.getdValue()) {

			logger.info("短线死叉(K,D):" + kdj_Info_Short.getkValue() + "|" + kdj_Info_Short.getdValue());

			if (kdj_Info_Mid.getdValue() < 60) {
				logger.info("中线D小于60. K,D:" + kdj_Info_Mid.getkValue() + "|" + kdj_Info_Mid.getdValue());
				return;
			}

			// 低于平均购入成本，卖出一半仓位，高于平均购入成本，全仓卖出
			double avg_price = account.getAvg_price();
			if (avg_price == 0)
				return;

			if (last_KLinePoint_Short.getLast() < avg_price) {
				// 卖出一半仓位
				account.sellCoinByPosition(last_KLinePoint_Short.getLast(), 0.5, System.currentTimeMillis());
				lastOperationTime = last_KLinePoint_Short.getUnixTime();
			} else {
				// 全仓卖出
				account.sellCoinByPosition(last_KLinePoint_Short.getLast(), 1, System.currentTimeMillis());
				lastOperationTime = last_KLinePoint_Short.getUnixTime();
			}

		} else {
			logger.info("短线趋势K,D:" + kdj_Info_Short.getkValue() + "|" + kdj_Info_Short.getdValue());
		}

	}

	public String getRunMode() {
		return runMode;
	}

	public void setRunMode(String runMode) {
		this.runMode = runMode;
	}

}
